#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <mh/common.h>
#include <mh/sram.h>
#include <mh/mac.h>
#include "knit.h"
#include <mh/mh_file.h>
#include "decript.h"
#include "prefixknit.h"
#include "backpiece.h"



/*
 * get economy of control data
 */
void GetEconomyData(MH_KNIT *p, ushort data[][3], int size)
{
    int i, j = 0;
    for(i = 0; i < p->total_line && j < size; ++i)
    {
        KNIT_PAGE *pcon = &p->knit_page[i];
        if(pcon->economy_start && pcon->economy_end && pcon->economy_num)
        {
            data[j][0] = pcon->economy_start;
            data[j][1] = pcon->economy_end;
            data[j][2] = pcon->economy_num;
            ++j;
        }
    }
}
/*
 * set economy of control data
 */
int SetEconomyData(MH_KNIT *p, ushort start, ushort end, ushort times)
{
    int ret = 0;
    KNIT_PAGE *con = p->knit_page_head;
    if(con)
    {
        if(times)
        {
            con[end].economy_start = start;
            con[end].economy_end = end;
            con[end].economy_num = times;
        }
        else
        {
            con[end].economy_start = 0;
            con[end].economy_end = 0;
            con[end].economy_num = 0;
        }
    }
    if(p->machine_ok)
    {
        if(p->communication == COMM_SRAM)
        {
            RunChangeParam(p);
        }
        else
        {
            ret = MacSetEconomy(p->pmac, p->total_line, start, end, times);
        }
    }
    return ret;
}
/*
 *
 */
int SetAllEconomyData(MH_KNIT *p, ushort data[][3], int size)
{
    int ret = 0;
    int h = 0;
    KNIT_PAGE *con = p->knit_page_head;
    /*清空本地和下位机有循环数据的控制页*/
     for(h = 0; h < p->total_line; ++h)
    {
        if(con[h].economy_end || con[h].economy_start || con[h].economy_num)
        {
            con[h].economy_start = 0;
            con[h].economy_end = 0;
            con[h].economy_num = 0;
            MacSendConLine(p->pmac, &con[h], p->total_line, h);
        }
    }
    for(h = 0; h < size; ++h)
    {
        printf("satrt:%d, end:%d\n",data[h][0], data[h][1]);
        if(data[h][0] <= p->total_line && data[h][1] <= p->total_line && data[h][0] < data[h][1])
        {
            p->knit_page_head[data[h][1]].economy_start = data[h][0];
            p->knit_page_head[data[h][1]].economy_end = data[h][1];
            p->knit_page_head[data[h][1]].economy_num = data[h][2];
            if(data[h][0] && data[h][1] && data[h][2])
            {
                ret = SetEconomyData(p, data[h][0], data[h][1], data[h][2]);
            }
        }
    }
    if(p->machine_ok)
    {
        if(p->communication == COMM_SRAM)
        {
            RunChangeParam(p);
        }
        else
        {
   //         ret =MacSendControlData(p->pmac, p->knit_page_head, p->total_line);
        }
    }
    return ret;
}
